﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using urBook.Engine;
namespace urBook.Gui
{
	/// <summary>
	/// Interaction logic for ContactView.xaml
	/// </summary>
	public partial class ContactView : UserControl
	{
        MainWindow root;
        public ContactCard contact { get; set; }
        public ContactCard backup { get; set; }

		public ContactView(MainWindow root, ContactCard contact)
		{
            Resources["ContactObject"] = contact;
            this.InitializeComponent();
            this.root = root;
            this.contact = (ContactCard)Resources["ContactObject"];
            backup = (ContactCard)contact.Clone();
            loadData();
            Save.IsEnabled = false;
            Revert.IsEnabled = false;
        }

        private void loadData()
        {
            if (contact.photo.url != "")
                setImageSource(image, contact.photo.url);

            foreach (Telephone t in contact.phones)
                phones.Items.Add(new ElementView(contact, t, "Telephone"));

            foreach (Email e in contact.emails)
                emails.Items.Add(new ElementView(contact, e, "Email"));

            if (contact.groups.Count > 0)
            {
                string groupsNames = "";
                foreach (string s in contact.groups)
                    groupsNames += s + "; ";
                groups.Text = groupsNames;
            }
        }

        private void setImageSource(Image image, string source)
        {
            BitmapImage src = new BitmapImage();
            src.BeginInit(); 
            src.UriSource = new Uri(source, UriKind.RelativeOrAbsolute); 
            src.CacheOption = BitmapCacheOption.OnLoad; 
            src.EndInit();
            image.Source = src;
            image.Stretch = Stretch.Uniform;
        }

        private void image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "image"; // Default file name
            dlg.DefaultExt = ".jpg"; // Default file extension
            dlg.Filter = "Images (*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG|" + "All files (*.*)|*.*";

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                string[] splits = filename.Split(new char[] { '.' });
                string ext = splits[splits.Length - 1];
                string imagePath = root.profilePath + "\\images\\" + contact.name.formattedName + "." + ext;
                System.IO.File.Copy(filename, imagePath, true);
                setImageSource(image, imagePath);
                contact.photo.url = imagePath;
                contact.photo.ext = ext;

                Save.IsEnabled = true;
                Revert.IsEnabled = true;
            }
        }

        private void AddPhone_Click(object sender, RoutedEventArgs e)
        {
            Telephone t = new Telephone();
            contact.phones.Add(t);
            phones.Items.Add(new ElementView(contact, t, "Telephone"));

            Save.IsEnabled = true;
            Revert.IsEnabled = true;
        }

        private void AddEmail_Click(object sender, RoutedEventArgs rea)
        {
            Email e = new Email();
            contact.emails.Add(e);
            emails.Items.Add(new ElementView(contact, e, "Email"));

            Save.IsEnabled = true;
            Revert.IsEnabled = true;
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            string[] groupsArray = this.groups.Text.Trim().Split(new string[] { "; " },StringSplitOptions.RemoveEmptyEntries);
            contact.groups.Clear();
            foreach(string s in groupsArray)
                contact.groups.Add(s);

            backup = (ContactCard)contact.Clone();
            Save.IsEnabled = false;
            Revert.IsEnabled = false;

            root.loadData();
        }

        private void Revert_Click(object sender, RoutedEventArgs e)
        {
            contact = (ContactCard)backup.Clone();
            Revert.IsEnabled = false;
            Save.IsEnabled = false;
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs args)
        {
            try
            {
                Save.IsEnabled = true;
                Revert.IsEnabled = true;
            }
            catch (NullReferenceException e)
            {

            }
        }

        private void PhonesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Telephone t = new Telephone();
            contact.phones.Add(t);
            phones.Items.Add(new ElementView(contact, t, "Telephone"));

            Save.IsEnabled = true;
            Revert.IsEnabled = true;
        }

        private void EmailsList_MouseDoubleClick(object sender, MouseButtonEventArgs args)
        {
            Email e = new Email();
            contact.emails.Add(e);
            emails.Items.Add(new ElementView(contact, e, "Email"));

            Save.IsEnabled = true;
            Revert.IsEnabled = true;
        }

        internal bool WindowClosing()
        {
            if (Save.IsEnabled)
            {
                String message = "Save changes to current contact?";
                String caption = "Save changes?";
                MessageBoxResult result = MessageBox.Show(message, caption, MessageBoxButton.YesNoCancel, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    root.openContacts.Remove(contact);
                    root.loadData();
                    return true;
                }
                else if (result == MessageBoxResult.No)
                {
                    contact = (ContactCard)backup.Clone();
                    root.openContacts.Remove(contact);
                    return true;
                }
                else
                    return false;
            }
            else
            {
                root.openContacts.Remove(contact);
                root.loadData();
                return true;
            }
        }
    }
}